package com.star.message.biz;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.star.common.core.contract.Page;
import com.star.common.kit.lang.ArrayKit;
import com.star.common.sms.contract.enums.TemplateStatusEnum;
import com.star.common.sms.contract.exception.SmsException;
import com.star.common.sms.contract.query.SmsSignPageQuery;
import com.star.common.sms.contract.vo.SmsSignDetailVO;
import com.star.common.sms.contract.vo.SmsSignPageVO;
import com.star.common.sms.factory.SmsFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * 短信签名业务逻辑
 *
 * @author zhouhengzhe
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsSignBizService {

    private final SmsFactory smsFactory;

    public static final ExecutorService COMMON_THREAD_POOL = new ThreadPoolExecutor(5, 5, 60,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), ThreadFactoryBuilder.create().setNamePrefix("async-future").build(), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * 分页查询短信签名
     *
     * @param smsSignPageQuery 分页查询参数
     * @return 分页结果
     */
    public Page<SmsSignPageVO> pageSmsSign(SmsSignPageQuery smsSignPageQuery) {
        Page<SmsSignPageVO> smsSignPageList = smsFactory.getAliyunSmsClient().pageSmsSign(smsSignPageQuery);
        if (CollectionUtils.isEmpty(smsSignPageList.getRecords())) {
            return Page.succeed(smsSignPageList.getRecords(), smsSignPageList.getTotal(), smsSignPageQuery.getCurrent(), smsSignPageQuery.getSize());
        }
        //异步调用
        List<CompletableFuture<SmsSignDetailVO>> completableFutures = smsSignPageList.getRecords()
                .stream()
                .map(smsSignPage -> CompletableFuture.supplyAsync(() ->
                        smsFactory.getAliyunSmsClient().querySmsSign(smsSignPage.getSignName()), COMMON_THREAD_POOL).exceptionally(e -> null)
                ).toList();
        CompletableFuture.allOf(ArrayKit.convert(completableFutures)).join();
        List<SmsSignDetailVO> smsSignDetailVo = completableFutures.stream().map(completableFuture -> {
            try {

                return completableFuture.exceptionally(e -> null).get();
            } catch (Exception e) {
                throw new SmsException(e);
            }
        }).toList();
        Map<String, SmsSignDetailVO> signDetailVoMap = Maps.uniqueIndex(smsSignDetailVo, SmsSignDetailVO::getSignName);
        List<SmsSignPageVO> smsSignPageVOList = Lists.newArrayList();
        for (SmsSignPageVO smsSignPageVO : smsSignPageList.getRecords()) {
            SmsSignDetailVO smsSignDetailVO = signDetailVoMap.get(smsSignPageVO.getSignName());
            if (Objects.nonNull(smsSignDetailVO) && TemplateStatusEnum.PASS.getCode().equals(smsSignDetailVO.getSignStatus())) {
                smsSignPageVOList.add(smsSignPageVO);
            }
        }
        //返回的数据跟实际的是不一样的，所以要搞成下划线的。
        return Page.succeed(smsSignPageVOList, smsSignPageList.getTotal(), smsSignPageQuery.getCurrent(), smsSignPageQuery.getSize());
    }
}
